package demo;

import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.general.find.PdfTextFind;
import com.spire.pdf.utilities.PdfTable;
import com.spire.pdf.utilities.PdfTableExtractor;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.junit.jupiter.api.Test;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @Classname Pdf
 * @Version 1.0.0
 * @Date 2022/2/23 0:21
 * @Created by yd
 */
public class Pdf {
    private String baseParth = "D:\\pdff\\20220223\\1211694718";
    private String pdfPath = baseParth + ".PDF";
    private String txtPath = baseParth + ".txt";

    @Test
    public void all() {
        List<String> strings = Arrays.asList("a", "b", "c");
        strings.stream().map(item -> CompletableFuture.runAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(ThreadLocalRandom.current().nextInt(5));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(StringUtils.repeat(item, 2));
        })).map(CompletableFuture::join).collect(Collectors.toList());
        //最后没有收集是不执行的
        System.out.println("CompletableFutureTest.all");
    }

    @Test
    public void pdfToTable() throws IOException {
        Collection<File> files = FileUtils.listFiles(new File("D:\\pdff\\20220223"), new String[]{"PDF"}, false);
        files.stream().map(item -> CompletableFuture.runAsync(() -> {
                    String name = item.getName();
                    String baseName = FilenameUtils.getBaseName(item.getAbsolutePath());
                    try {
                        String parent = item.getParent();
                        getTableFromPdf(parent + "/" + name, parent + "/" + baseName + ".txt");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }))
                .map(CompletableFuture::join)
                .collect(Collectors.toList());

    }

    @Test
    public void parseSingle() throws IOException {
        String pdfPath = "D:/pdff/20220223/隆基股份：关于控股股东减持公司可转换公司债券的提示性公告.pdf";
        pdfPath = "D:/pdff/20220223/1212046117.PDF";
        pdfPath = "D:/隆基股份.pdf";
        getTableFromPdf(pdfPath, "d:/lg.txt");
    }

    /**
     * 表格不完整，获取不到 持有人|https://cdn.jsdelivr.net/gh/qianlicao51/files@main/img/202202240105310.png
     *
     * @param pdfPath
     * @param txtPath
     * @throws IOException
     */
    private void getTableFromPdf(String pdfPath, String txtPath) throws IOException {
        //实例化PdfDocument类的对象
        PdfDocument pdf = new PdfDocument();
        //加载PDF文档
        pdf.loadFromFile(pdfPath);
        //创建StringBuilder类的实例
        StringBuilder builder = new StringBuilder();
        //创建PdfTableExtractor类的对象
        PdfTableExtractor extractor = new PdfTableExtractor(pdf);
        //遍历每一页
        for (int page = 0; page < pdf.getPages().getCount(); page++) {
            //提取页面中的表格存入PdfTable[]数组
            PdfTable[] tableLists = extractor.extractTable(page);
            if (tableLists != null && tableLists.length > 0) {
                //遍历表格
                for (PdfTable table : tableLists) {
                    int row = table.getRowCount();//获取表格行
                    int column = table.getColumnCount();//获取表格列
                    for (int i = 0; i < row; i++) {
                        for (int j = 0; j < column; j++) {
                            //获取表格中的文本内容
                            String text = table.getText(i, j);
                            //将获取的text写入StringBuilder容器
                            //replaceAll("//r|//n", "")
                            String replace = StringUtils.replaceEach(text, new String[]{"\n", ",", "%"}, new String[]{"", "", ""});
                            System.out.print(replace + " ");
                            builder.append(replace + "|");
                        }
                        System.out.println();
                        builder.append(System.getProperty("line.separator"));
                    }
                }
            }
        }
        //保存为txt文档
        FileWriter fileWriter = new FileWriter(txtPath);
        fileWriter.write(builder.toString());
        fileWriter.flush();
        fileWriter.close();
    }

    @Test
    public void replace() {
        String tring = "本次减持前\n" +
                "持有数量\n" +
                "（张）";

        System.out.println(StringUtils.replaceEach(tring, new String[]{"\n"}, new String[]{""}));
    }

    /**
     * 查找并高亮|解析转债code name
     * https://www.e-iceblue.cn/pdf_java_text/find-and-highlight-selected-text-in-pdf-in-java.html
     */
    @Test
    public void findAndHighlightText() {
        //加载示例PDF文档
        // "D:/pdff/20220223/隆基股份：关于控股股东减持公司可转换公司债券的提示性公告.pdf"
        Collection<File> files = FileUtils.listFiles(new File("D:\\pdff\\20220223"), new String[]{"PDF", "pdf"}, false);
        files.stream()
                .map(item -> CompletableFuture.runAsync(() -> {
                    getCodeAndNameFromPdf(item.getAbsolutePath());
                }))
                .map(CompletableFuture::join)
                .collect(Collectors.toList());

    }

    private void getCodeAndNameFromPdf(String filePath) {
        PdfDocument pdf = new PdfDocument();
        pdf.loadFromFile(filePath);
        // pdf.loadFromFile("D:/pdff/20220223/1212401799.PDF");
        //遍历文档页面|只需要第一页就可以获取名字
        PdfPageBase pdfPageBase = pdf.getPages().get(0);
        PdfTextFind[] finds = pdfPageBase.findText("代码").getFinds();

        //多次循环只能最后一次，因为|https://cdn.jsdelivr.net/gh/qianlicao51/files@main/img/202202240009380.png
        String kzzCode = "";
        String kzzName = "";
        for (PdfTextFind find : finds) {
            String lineText = find.getLineText();
            // System.out.println(lineText);
            lineText = StringUtils.trimToEmpty(lineText);
            //将 " 债券代码：113627          债券简称：太平转债"  更改为 “债券代码|113627          债券简称|太平转债”
            lineText = StringUtils.replaceEach(lineText, new String[]{":", "："}, new String[]{"|", "|"});
            //有些是 “债券代码” ，少部分是 "转债代码"
            if (StringUtils.startsWithAny(lineText, "债券代码", "转债代码")) {
                // 从中提取 可转债代码和名称
                // String kzzCode = StringUtils.getDigits(lineText);
                kzzCode = StringUtils.substring(lineText, 5, 11);
                kzzName = StringUtils.substringAfter(lineText, "简称|");
            }
        }
        System.out.println("code=" + kzzCode + " name=" + kzzName);
        System.out.println(StringUtils.center("-", 100, "*"));
    }
}
